/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-12 21:02:05
 * @LastEditTime: 2025-05-20 21:43:23
 * @FilePath: /monitor_belt/src/views/home/index.tsx
 */

import { Flex } from "antd";
import styles from "./index.module.scss";
import News from "./components/news";
import DataDnDFlow from "./components/ware";
import { useEffect, useRef, useState } from "react";
import RunState from "./components/run_state";
import { remoteLatestAlarm } from "@/api/message";
import { getCache, removeCache, setCache } from "@/utils/storage";
import { useStore } from "@/store/conveyor";
import Alarm from "@/assets/alarm.mp3";
import VideoStream from "./components/video-stream";
import { remoteCameraInfo } from "@/api/system";

let timer: any = null;
let status: boolean = false;
const Home = () => {
  const [videoList, setVideoList] = useState<string[]>([""]);
  const [allRecords, setAllRecords] = useState<any[]>([]);
  const [warnRecords, setWarnRecords] = useState<any[]>([]);
  const audioRef = useRef(null);

  const unsubscribe = useStore.subscribe((state) => {
    status = state.status;
    if (status) {
      handlePlayPause();
    }
  });

  useEffect(() => {
    removeCache("latest");
    getDeviceInfo();
    getLatestNews();
    return () => {
      // 记得在不需要时取消订阅
      unsubscribe();
      clearTimeout(timer);
    };
  }, []);

  const getLatestNews = async () => {
    try {
      let res = await remoteLatestAlarm(1);
      let { data } = res;
      if (data?.length) {
        let item = data[0]
        let latest = getCache("latest");
        if (!latest || latest.id != item.id) {
          handlePlay();
          setCache("latest", item);
          setAllRecords((prevList: any[]) => {
            return [...prevList, item];
          });
          if (item.alarm_type == 3) {
            setWarnRecords((prevList: any[]) => {
              return [...prevList, item];
            });
          }
        }
      }
    } finally {
      timer = setTimeout(() => {
        getLatestNews();
      }, 1000 * 4);
    }
  };

  const uniqueItems = (items: any[]) => {
    return Array.from(new Set(items.map((item) => item.id))).map((id) => {
      return items.find((item) => item.id == id);
    });
  };

  const handlePlayPause = () => {
    const audioElement = audioRef.current;
    audioElement.play();
    audioElement.pause();
  };
  const handlePlay = () => {
    if (status) {
      const audioElement = audioRef.current;
      audioElement.play();
    }
  };

  //获取设备参数
  const getDeviceInfo = async()=>{
    try{
      let res = await remoteCameraInfo();
      setVideoList(res.data)
    }finally{}
  }

  return (
    <Flex gap={10} vertical flex={1} style={{ margin: "10px 10px 0 10px" }}>
      <Flex gap={10} flex={5} style={{ overflow: "hidden" }}>
        <Flex gap={10} flex={3}>
          {videoList.map((item: string, index: number) => {
            return (
              <Flex flex={1} className={styles.video_item} key={index}>
                <VideoStream info={item} />
              </Flex>
            );
          })}
        </Flex>
        <Flex flex={1}>
          <News list={[...uniqueItems(allRecords)]} />
        </Flex>
      </Flex>
      <audio ref={audioRef} src={Alarm}>
        Your browser does not support the audio element.
      </audio>
      <Flex flex={2} style={{ flexShrink: 0 }} gap={10}>
        <Flex flex={3} gap={10}>
          <Flex flex={2} className={styles.notice}>
            <RunState />
          </Flex>
          <Flex flex={5} className={styles.notice}>
            <News list={[...uniqueItems(warnRecords)]} />
          </Flex>
        </Flex>
        <Flex flex={1} className={styles.notice}>
          <DataDnDFlow />
        </Flex>
      </Flex>
    </Flex>
  );
};

export default Home;
